import React from 'react';
import _ from 'lodash';
import { Button, Modal, Space, Table, TableProps, message } from 'antd';
import {
  FormPanel,
  type FormPanelObject,
  FormPanelStatus,
  InputType,
  FormPanelBtnAlign,
  FormPanelBtnDisplay,
} from 'lfun-bg-comp';
import dayjs from 'dayjs';
import { useLocation, useParams } from 'react-router-dom';
import { SCHOOL_LEADER_POSITION, SCHOOL_LEADER_STATUS } from '@/constant/schoolOptions';
import styles from './index.less';
import utils, { get_stoge_pz, set_stoge_pz } from '@/utils';
import { Leader, createLeader, deleteLeader, searchLeader, updateLeader } from '@/service/unit/leader';
import { PAGINATIONCONFIG } from '@/constant/page';
import { isPermissionOperate } from '@/component/permission-button';

// eslint-disable-next-line react/require-default-props
const Groups: React.FC<{ value?: any; onChange?: Function; isEdit?: boolean }> = ({
  value,
  onChange,
  isEdit = true,
}) => {
  const location = useLocation();
  const [showModel, setShowModel] = React.useState(false);
  const [showEditModel, setShowEditModel] = React.useState(false);
  const [showNewModel, setShowNewModel] = React.useState(false);
  const [datasource, setDatasource] = React.useState([]);
  const [total, setTotal] = React.useState(0);
  const [pageSize, setPageSize] = React.useState(get_stoge_pz(10, 'add-leader'));
  const [pageIndex, setPageIndex] = React.useState(1);
  const [currentValue, setCurrentValue] = React.useState({});
  const { id } = useParams();
  const newFileds = [
    {
      title: '',
      labelCol: { span: 6 },
      wrapperCol: { span: 18 },
      span: 24,
      inputs: [
        {
          label: '领导姓名',
          name: 'leader_name',
          key: 'leader_name',
          required: true,
          textRange: [0, 10],
        },
        {
          label: '职务',
          name: 'position',
          key: 'position',
          span: 24,
          required: true,
          inputType: InputType.select,
          renderOption: SCHOOL_LEADER_POSITION,
        },
        {
          label: '状态',
          name: 'status',
          key: 'status',
          required: true,
          inputType: InputType.select,
          renderOption: SCHOOL_LEADER_STATUS,
        },
        {
          label: '任职开始时间',
          name: 'start_date',
          key: 'start_date',
          inputType: InputType.date,
        },
        {
          label: '任职结束时间',
          name: 'end_date',
          key: 'end_date',
          inputType: InputType.date,
        },
        {
          label: '工作内容',
          name: 'job_content',
          key: 'job_content',
          inputType: InputType.textarea,
          textRange: [0, 100],
          inputProps: {
            autoSize: { minRows: 2, maxRows: 6 },
          },
        },
        {
          label: '分管工作',
          name: 'job_responsibility',
          key: 'job_responsibility',
          inputType: InputType.textarea,
          textRange: [0, 100],
          inputProps: {
            autoSize: { minRows: 2, maxRows: 6 },
          },
        },
      ],
    },
  ];
  const columns: TableProps['columns'] = [
    {
      title: '领导姓名',
      key: 'leader_name',
      dataIndex: 'leader_name',
      fixed: 'left',
      width: 100,
    },
    {
      title: '状态',
      key: 'status',
      dataIndex: 'status',
      width: 100,
      render: (text: any) => {
        return _.find(SCHOOL_LEADER_STATUS, { value: String(text) })?.label;
      },
    },
    {
      title: '职务',
      key: 'position',
      dataIndex: 'position',
      width: 120,
      render: (text: any) => {
        return _.find(SCHOOL_LEADER_POSITION, { value: String(text) })?.label;
      },
    },
    {
      title: '任开始时间',
      key: 'start_date',
      dataIndex: 'start_date',
      width: 100,
    },
    {
      title: '任结束时间',
      key: 'end_date',
      dataIndex: 'end_date',
      width: 100,
    },
    {
      title: '工作内容',
      key: 'job_content',
      dataIndex: 'job_content',
      width: 200,
      render(value) {
        return <div style={{ width: 200 }}>{value}</div>;
      },
    },
    {
      title: '分工',
      width: 200,
      key: 'job_responsibility',
      dataIndex: 'job_responsibility',
      render(value) {
        return <div style={{ width: 200 }}>{value}</div>;
      },
    },
  ];

  const edit_colums: TableProps['columns'] = [
    {
      title: '操作',
      key: 'operation',
      dataIndex: 'operation',
      fixed: 'right',
      //width: 200,
      align: 'center',
      hidden: !isPermissionOperate(),
      render: (text, record: Leader) => {
        return (
          <Space>
            <Button
              key="look"
              type="link"
              size="small"
              onClick={() => {
                setCurrentValue({ ...record });
                setShowModel(true);
              }}
            >
              查看
            </Button>
            {isEdit ? (
              <>
                <Button
                  key="edit"
                  type="link"
                  size="small"
                  onClick={() => {
                    setCurrentValue({ ...record });
                    setShowEditModel(true);
                  }}
                >
                  编辑
                </Button>
                <Button
                  key="del"
                  type="link"
                  size="small"
                  onClick={() => {
                    Modal.confirm({
                      title: '删除',
                      content: `确定否删除‘${record.leader_name}’的相关信息`,
                      onOk: async () => {
                        const r = await deleteLeader(record.id);
                        if (r?.success) {
                          message.success('删除成功');
                          search({
                            page: pageIndex,
                            per_page: pageSize,
                          });
                        } else {
                          message.error(r.message);
                          throw new Error();
                        }
                      },
                    });
                  }}
                >
                  删除
                </Button>
              </>
            ) : (
              ''
            )}
          </Space>
        );
      },
    },
  ];
  React.useEffect(() => {
    search({
      page: pageIndex,
      per_page: pageSize,
    });
  }, []);

  const search = async (params: any) => {
    const res = await searchLeader(id, params.page, params.per_page);
    if (res.success) {
      setDatasource(res.data.items);
      setPageIndex(params.page);
      setPageSize(params.per_page);
      setTotal(res.data.total);
    }
  };
  const pageChange = (pageIndex, pageSize) => {
    set_stoge_pz(pageSize, 'add-leader');
    search({
      page: pageIndex,
      per_page: pageSize,
    });
  };
  return (
    <>
      {isEdit ? (
        <Button
          style={{ display: 'block' }}
          type="primary"
          className={`${styles.add_leader_btn} add_leader_btn`}
          onClick={() => setShowNewModel(true)}
        >
          新增领导
        </Button>
      ) : (
        ''
      )}
      <Table
        dataSource={datasource}
        columns={columns.concat(edit_colums)}
        scroll={{ x: 'max-content' }}
        pagination={{ ...PAGINATIONCONFIG, total, pageSize, current: pageIndex, onChange: pageChange }}
      />
      <Modal title="新增领导" footer={[]} open={showNewModel} onCancel={() => setShowNewModel(false)}>
        <FormPanel
          template={newFileds}
          key={1}
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="返回"
          submitBtnText="确定"
          onFinish={async (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            const update = { planning_school_id: location.state.id, ...values };
            update.start_date = dayjs(update.start_date).format('YYYY-MM-DD');
            update.end_date = dayjs(update.end_date).format('YYYY-MM-DD');
            const res = await createLeader(update);
            if (res.success) {
              message.success('添加成功');
              setShowNewModel(false);
              formPanelObject.resetFields();
              search({
                page: pageIndex,
                per_page: pageSize,
              });
            } else {
              formPanelObject.reVaildation(res);
            }
            return res.success;
          }}
          onReset={() => {
            setShowNewModel(false);
          }}
        />
      </Modal>
      <Modal title="修改领导" footer={[]} open={showEditModel} onCancel={() => setShowEditModel(false)}>
        <FormPanel
          template={newFileds}
          key={1}
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="返回"
          submitBtnText="确定"
          values={currentValue}
          onFinish={async (formPanelObject: FormPanelObject) => {
            const values = formPanelObject.getFieldsValue();
            utils.showLoading();
            const update = { ...currentValue, ...values };
            if (update.start_date) update.start_date = dayjs(update.start_date).format('YYYY-MM-DD');
            if (update.end_date) update.end_date = dayjs(update.end_date).format('YYYY-MM-DD');
            const res = await updateLeader(update);
            if (res.success) {
              message.success('修改成功');
              setShowEditModel(false);
              formPanelObject.resetFields();
              search({
                page: pageIndex,
                per_page: pageSize,
              });
            } else {
              formPanelObject.reVaildation(res);
            }
            utils.hideLoaing(res.success);
            return res.success;
          }}
          onReset={() => setShowEditModel(false)}
        />
      </Modal>
      <Modal title="查看领导" footer={[]} open={showModel} onCancel={() => setShowModel(false)}>
        <FormPanel
          template={newFileds}
          key={1}
          btnsAlign={FormPanelBtnAlign.center}
          buttonsDisplay={FormPanelBtnDisplay.block}
          restBtnText="返回"
          submitBtnText="确定"
          values={currentValue}
          formStatus={FormPanelStatus.nonEdit}
          onReset={() => setShowModel(false)}
        />
      </Modal>
    </>
  );
};

export default Groups;
